﻿using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.Mvc;
using eduscrum.Models;
using eduscrum.DAL;
using eduscrum.Helper;
using eduscrum.ViewModels;
using System;

namespace eduscrum.Controllers
{
    public class BoardController : Controller
    {
        private SystemContext db = new SystemContext();//Make DB content available
        //
        // GET: /Board/

        public ActionResult Index(int id, int sprintID = -1)
        {
            Sprint sprint = new Sprint();
            if (sprintID > 0)
            {
                sprint = db.Sprints.Find(sprintID);
            }
            else
            {
                sprint = db.Sprints.Where(s => s.Project.ProjectID == id).OrderBy(s => s.SprintID).First();
            }

            SprintVM sprintVM = new SprintVM();
            AutoMapper.Mapper.Map(sprint, sprintVM);

            /*
             * Sprint DDL
             */
            int sprintCounter = 1;
            List<SelectListItem> ddlList = new List<SelectListItem>();
            List<Sprint> sprints = sprint.Project.Sprints.OrderBy(s => s.SprintID).ToList();

            for (int i = 0; i < sprints.Count; i++)
            {
                SelectListItem item = new SelectListItem { Text = "Sprint " + sprintCounter, Value = sprints[i].SprintID.ToString() };
                item.Selected = false;
                if (item.Value.Equals(sprint.SprintID.ToString()))
                {
                    item.Selected = true;
                }
                ddlList.Add(item);
                sprintCounter++;
            }

            ViewData["SprintsDDL"] = ddlList;
            /*
             * END Sprint DDL 
             */
            return View(sprintVM);
        }

        [HttpPost]
        public string UpdateUserStoryPhase(string usID, string phaseName)
        {
            //find phase id from current project using projectid, to validate    
            
            var userstory = db.UserStories.Find(Convert.ToInt16(usID));
            var proj = userstory.Project;
            var phases = proj.Phases;
            var phase = phases.Find(p => p.Name.Equals(phaseName));
            int projetID = proj.ProjectID;
            
            userstory.Phase = phase;
            db.Entry(userstory).State = EntityState.Modified;
            db.SaveChanges();            
            return string.Empty;//empty string as response
        }
    }
}
